package filter;

import beans.User;
import jakarta.servlet.*;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import service.UserService;
import utils.CookieUtils;

import java.io.IOException;

public class AutoLoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将servletRequest和ServletResponse向下转型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //判断用户的登录状态（也就是判断Session里面是否有用户）
        User existUser = (User) request.getSession().getAttribute("existUser");

        if (existUser!=null){
            filterChain.doFilter(request,response);
        }else {
            Cookie cookie = CookieUtils.getCookie("autoLogin", request.getCookies());
            if (cookie==null) {
                filterChain.doFilter(request,response);
            }else {
                String[] values = cookie.getValue().split("#");

                //从cookie中取出账号和密码 做登录操作  去和数据库匹配
                UserService userService = new UserService();
                User user = userService.login(new User(values[0], values[1]));
                if (user==null){
                    filterChain.doFilter(request,response);
                }else{
                    request.getSession().setAttribute("existUser",user);
                    filterChain.doFilter(request,response);
                }
            }
        }

    }
}
